package com.xiyuan.smartutils.template.engine.statement;

import com.xiyuan.smartutils.Types;
import com.xiyuan.smartutils.template.engine.StatementParser;
import com.xiyuan.smartutils.template.engine.TagType;
import com.xiyuan.smartutils.template.engine.VariableMap;
import com.xiyuan.smartutils.template.engine.exception.StatementException;

import java.io.PrintWriter;
import java.util.Iterator;

public class _IF_ELSE_IF extends _IF
{
    private static final long serialVersionUID = 1L;
    
    public _IF_ELSE_IF(StatementParser statementParser)
    {
        super(statementParser);
    }
    
    @Override
    public void addStatement(Statement stmt)
    {
        if (stmt == null)
            return;
        
        if (stmt.getType() == TagType.ELSEIF || stmt.getType() == TagType.ELSE)
            this.getParent().addStatement(stmt);
        else
            super.addStatement(stmt);
    }
    
    /**
     * 判断是否满足条件
     */
    boolean is(VariableMap page)
    {
        if (expressions.isEmpty())
            throw new StatementException(getPath(), getLineNo(), getBeginColumn(), getType() + "缺少条件表达式");
        
        Object condition = expressions.get(0).execute(page);
        // 表达式为null表示不检查所有的if,elseif,else，如item.isTrue()时item==null导致方法返回null
        if (condition == null)
            return false;
        
        // 不是null，则检查是不是布尔型，如果不是报异常
        if (!Types.isBoolean(condition))
            throw new StatementException(getPath(), getLineNo(), getBeginColumn(), getType() + "中表达式" + expressions.get(0) + "，格式不正确，不是布尔型");
        
        return (Boolean) condition;
    }
    
    @Override
    protected void build(VariableMap variableMap, PrintWriter out)
    {
        if (!hasChild())
            return;
        
        try
        {
            variableMap.newVariableSpace();// 创建局部变量空间
            Iterator<Statement> iterator = childs.iterator();
            while (iterator.hasNext())
            {// 循环内容
                Statement stmt = iterator.next();
                stmt.execute(variableMap, out);
            }
            
        }
        finally
        {
            // 销毁局部变量空间
            variableMap.releaseVariableSpace();
        }
        
    }
    
    @Override
    public TagType getType()
    {
        return TagType.ELSEIF;
    }
}
